<template>
  <div v-loading="loading">
    <el-page-header class="project-page-head" @back="$router.back()" title="项目视图">
      <template #content>
        <span style="font-weight: 600;">{{ project.name }}</span>
      </template>
      <template #extra>
        <el-button v-if="DeletePojectPermissions" type="danger" plain @click="openDeleteProjectConfirmMessageBox">
          <el-icon>
            <Delete />
          </el-icon>
        </el-button>
      </template>
    </el-page-header>
    <section class="info-container">
      <el-descriptions class="descriptions-list" size="large" border>
        <template #title>
          <div class="descriptions-title">
            <el-icon class="descriptions-title-icon">
              <View />
            </el-icon>
            <span>项目信息</span>
          </div>
        </template>
        <template #extra>
          <el-button @click="openEditProjectDialog" v-if="ChangeProjectInformationPermissions">
            <el-icon>
              <Edit />
            </el-icon>
          </el-button>
        </template>
        <el-descriptions-item label="项目编号">{{ project.id }}</el-descriptions-item>
        <el-descriptions-item label="项目名称">{{ project.name }}</el-descriptions-item>
        <el-descriptions-item label="负责人">{{ project.leader.name }}</el-descriptions-item>
        <el-descriptions-item label="立项时间">{{ strDate(project.start_time) }}</el-descriptions-item>
        <el-descriptions-item label="当前版本">
          <el-tag size="small">{{ project.current_version }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="project.top_designer != undefined" :label="project.top_designer.called">
          {{ project.top_designer.user.name }}
        </el-descriptions-item>
      </el-descriptions>
    </section>
    <!-- 简介 -->
    <section class="info-container">
      <el-descriptions class="descriptions-list" size="large" border>
        <template #title>
          <div class="descriptions-title">
            <el-icon class="descriptions-title-icon">
              <Cpu />
            </el-icon>
            <span>简介</span>
          </div>
        </template>
        <template #extra>
          <el-button @click="openEditProjectDetailDialog" v-if="ChangeProjectInformationPermissions">
            <el-icon>
              <Edit />
            </el-icon>
          </el-button>
        </template>
      </el-descriptions>
      <!-- <div class="project-detail">
      {{ project.detail }}
    </div> -->
      <div v-html="projectDetail" class="project-detail"></div>
    </section>
    <!-- 文档 -->
    <section class="info-container">
      <el-descriptions class="descriptions-list" size="large" border>
        <template #title>
          <div class="descriptions-title">
            <el-icon class="descriptions-title-icon">
              <Document />
            </el-icon>
            <span>文档</span>
          </div>
        </template>
        <template #extra v-if="ChangeProjectInformationPermissions">
          <el-button @click="toggleAddDocumentInterface">
            <el-icon>
              <Plus />
            </el-icon>
          </el-button>
          <el-button @click="toggleDocumentTableEdit">
            <el-icon v-if="documentTableEditEndable">
              <Check />
            </el-icon>
            <el-icon v-else>
              <Edit />
            </el-icon>
          </el-button>
        </template>
      </el-descriptions>
      <el-table :data="documentList" border>
        <el-table-column prop="name" label="名字">
          <template v-slot="scope">
            <el-input v-if="scope.row.inTableEdit != undefined" v-model="scope.row.inTableEdit.name"></el-input>
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="href" label="链接">
          <!-- <template v-slot="scope">
          <el-input v-if="scope.row.inTableEdit != undefined" v-model="scope.row.inTableEdit.href"></el-input>
          <span v-else>{{ scope.row.href }}</span>
        </template> -->
          <template v-slot="scope">
            <el-input v-if="scope.row.inTableEdit != undefined" v-model="scope.row.inTableEdit.href"></el-input>
            <el-link v-else type="primary" :href="scope.row.href" target="_blank" :underline="false">{{ scope.row.href
            }}</el-link>
            <!-- <span v-else>{{ scope.row.href }}</span> -->
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="documentTableEditEndable">
          <template v-slot="scope">
            <el-button type="primary" circle @click="toggleInDocumentTableEdit(scope.row)">
              <el-icon v-if="scope.row.inTableEdit == undefined">
                <Edit />
              </el-icon>
              <el-icon v-else>
                <Check />
              </el-icon>
            </el-button>
            <el-button type="danger" circle @click="openDeleteDocumentConfirmMessageBox(scope.row)">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="add-technology-box" v-if="addDocumentBarEnable">
        <div class="add-technology-left">
          <el-input v-model="documentName" placeholder="文档名字"></el-input>
          <el-input v-model="documentHref" placeholder="文档链接"></el-input>

        </div>
        <div class="add-technology-right">
          <el-button @click="addDocument">添加</el-button>
          <el-button @click="toggleAddDocumentInterface">取消</el-button>
        </div>
      </div>
    </section>
    <!-- 代码仓库 -->
    <section class="info-container">
      <el-descriptions class="descriptions-list" size="large" border>
        <template #title>
          <div class="descriptions-title">
            <el-icon class="descriptions-title-icon">
              <Box />
            </el-icon>
            <span>代码仓库</span>
          </div>
        </template>
        <template #extra v-if="ChangeProjectInformationPermissions">
          <el-button @click="toggleAddRepositoryInterface">
            <el-icon>
              <Plus />
            </el-icon>
          </el-button>
          <el-button @click="toggleRepositoryTableEdit">
            <el-icon v-if="repositoryTableEditEndable">
              <Check />
            </el-icon>
            <el-icon v-else>
              <Edit />
            </el-icon>
          </el-button>
        </template>
      </el-descriptions>
      <el-table :data="repositoryList" border>
        <el-table-column prop="name" label="名字">
          <template v-slot="scope">
            <el-input v-if="scope.row.inTableEdit != undefined" v-model="scope.row.inTableEdit.name"></el-input>
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="href" label="链接">
          <template v-slot="scope">
            <el-input v-if="scope.row.inTableEdit != undefined" v-model="scope.row.inTableEdit.href"></el-input>
            <!-- <span v-else>{{ scope.row.href }}</span> -->
            <el-link v-else type="primary" :href="scope.row.href" target="_blank" :underline="false">{{ scope.row.href
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="repositoryTableEditEndable">
          <template v-slot="scope">
            <el-button type="primary" circle @click="toggleInRepositoryTableEdit(scope.row)">
              <el-icon v-if="scope.row.inTableEdit == undefined">
                <Edit />
              </el-icon>
              <el-icon v-else>
                <Check />
              </el-icon>
            </el-button>
            <el-button type="danger" circle @click="openDeleteRepositoryConfirmMessageBox(scope.row)">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="add-technology-box" v-if="addRepositoryBarEnable">
        <div class="add-technology-left">
          <el-input v-model="repositoryName" placeholder="仓库名字"></el-input>
          <el-input v-model="repositoryHref" placeholder="仓库链接"></el-input>

        </div>
        <div class="add-technology-right">
          <el-button @click="addRepository">添加</el-button>
          <el-button @click="toggleAddRepositoryInterface">取消</el-button>
        </div>
      </div>
    </section>
    <!-- 项目身份 -->
    <section class="info-container">
      <el-descriptions class="descriptions-list" size="large" border>
        <template #title>
          <div class="descriptions-title">
            <el-icon class="descriptions-title-icon">
              <Service />
            </el-icon>
            <span>项目身份</span>
          </div>
        </template>
        <template #extra v-if="ProRolePermission">
          <el-button @click="toggleAddProjectRoleBox">
            <el-icon>
              <Plus />
            </el-icon>
          </el-button>
          <el-button @click="toggleProjectRoleEidt">
            <el-icon v-if="projectRoleTableEditEndable">
              <Check />
            </el-icon>
            <el-icon v-else>
              <Edit />
            </el-icon>
          </el-button>
        </template>
      </el-descriptions>
      <el-table :data="projectRoles" style="width: 100%" border>
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="name" label="角色">
          <template v-slot="scope">
            <el-input v-if="scope.row.inTableEdit != undefined" v-model="scope.row.inTableEdit.name"></el-input>
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column v-for="permission in projectPermissionList" :key="permission.id">
          <template #header>
            <el-tooltip class="box-item" effect="dark" placement="top" :content="permission.detail">{{
              permission.name }}</el-tooltip>
          </template>
          <template #default="scope">
            <el-checkbox v-if="scope.row.inTableEdit != undefined"
              v-model="scope.row.inTableEdit.inTableRecordProjectPermissions[permission.id]" :true-label="1"
              :false-label="0" size="large" />
            <span v-else>{{ scope.row.permissions.indexOf(permission.id) > -1 ? 'YES' : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="projectRoleTableEditEndable">
          <template v-slot="scope">
            <el-button type="primary" circle @click="toggleInprojectRoleTableEdit(scope.row)">
              <el-icon v-if="scope.row.inTableEdit == undefined">
                <Edit />
              </el-icon>
              <el-icon v-else>
                <Check />
              </el-icon>
            </el-button>
            <el-button type="danger" circle @click="openDeleteprojectRoleConfirmMessageBox(scope.row)">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="add-role-box" v-if="addProjectRoleWidget.enable">
        <div class="add-role-left">
          <el-input class="add-role-left-input" v-model="addProjectRoleWidget.form.name" placeholder="项目身份" />
        </div>
        <div class="add-role-right">
          <el-button @click="addProjectRole">添加</el-button>
          <el-button @click="toggleAddProjectRoleBox">取消</el-button>
        </div>
      </div>
    </section>

    <!-- 成员 -->
    <section class="info-container">
      <el-descriptions class="descriptions-list" size="large" border>
        <template #title>
          <div class="descriptions-title">
            <el-icon class="descriptions-title-icon">
              <Star />
            </el-icon>
            <span>成员</span>
          </div>
        </template>
        <template #extra v-if="ProjectMemberPermissions">
          <el-button @click="toggleAddMemberInterface">
            <el-icon>
              <Plus />
            </el-icon>
          </el-button>
          <el-button @click="toggleMemberTableEdit">
            <el-icon v-if="memberTableEditEndable">
              <Check />
            </el-icon>
            <el-icon v-else>
              <Edit />
            </el-icon>
          </el-button>
        </template>
      </el-descriptions>
      <el-table :data="project.members" border>
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="name" label="名字" />
        <el-table-column prop="role.name" label="身份">
          <template #default="scope">
            <el-select v-if="scope.row.inTableEdit != undefined" v-model="scope.row.inTableEdit.role.id">
              <el-option v-for="role in projectRoles" :key="role.id" :label="role.name" :value="role.id" />
            </el-select>
            <span v-else>{{ scope.row.role.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template #default="scope">
            <el-input v-if="scope.row.inTableEdit != undefined" v-model="scope.row.inTableEdit.annotation"
              placeholder="在项目中的工作内容" />
            <span v-else>{{ scope.row.annotation }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="memberTableEditEndable">
          <template v-slot="scope">
            <el-button type="primary" circle @click="toggleInMemberTableEdit(scope.row)">
              <el-icon v-if="scope.row.inTableEdit == undefined">
                <Edit />
              </el-icon>
              <el-icon v-else>
                <Check />
              </el-icon>
            </el-button>
            <el-button type="danger" circle @click="openDeleteMemberConfirmMessageBox(scope.row)">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="add-technology-box" v-if="addMemberBarEnable">
        <div class="add-technology-left">
          <el-select class="add-technology-left-select" v-model="userSelect" placeholder="选择成员">
            <el-option v-for="user in users" :key="user.id" :label="user.name" :value="user.id" />
          </el-select>
          <el-select v-model="userRid" placeholder="项目身份">
            <el-option v-for="role in projectRoles" :key="role.id" :label="role.name" :value="role.id" />
          </el-select>
          <el-input class="add-technology-left-input" v-model="userAnnotation" placeholder="在项目中的工作内容" />
        </div>
        <div class="add-technology-right">
          <el-button @click="addMember">添加</el-button>
          <el-button @click="toggleAddMemberInterface">取消</el-button>
        </div>
      </div>
    </section>
    <!-- 技术 -->
    <section class="info-container">
      <el-descriptions class="descriptions-list" size="large" border>
        <template #title>
          <div class="descriptions-title">
            <el-icon class="descriptions-title-icon">
              <Key />
            </el-icon>
            <span>技术</span>
          </div>
        </template>
        <template #extra v-if="ChangeProjectInformationPermissions">
          <el-button @click="toggleAddTechnologyInterface">
            <el-icon>
              <Plus />
            </el-icon>
          </el-button>
          <el-button @click="toggleTechnologyTableEdit">
            <el-icon v-if="technologyTableEditEndable">
              <Check />
            </el-icon>
            <el-icon v-else>
              <Edit />
            </el-icon>
          </el-button>
        </template>
      </el-descriptions>
      <el-table :data="project.technologies" border>
        <el-table-column prop="id" label="ID" />
        <el-table-column label="技术">
          <template #default="scope">
            <router-link :to="`/technologies/${scope.row.id}`">
              <span>{{ scope.row.name }}</span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template v-slot="scope">
            <el-input v-if="scope.row.inTableEdit != undefined" v-model="scope.row.inTableEdit.annotation"
              placeholder="技术在项目中的使用情况" />
            <span v-else>{{ scope.row.annotation }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="technologyTableEditEndable">
          <template v-slot="scope">
            <el-button type="primary" circle @click="toggleInTableEdit(scope.row)">
              <el-icon v-if="scope.row.inTableEdit == undefined">
                <Edit />
              </el-icon>
              <el-icon v-else>
                <Check />
              </el-icon>
            </el-button>
            <el-button type="danger" circle @click="deleteTechnology(scope.row.id)">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="add-technology-box" v-if="addTechnologyBarEnable">
        <div class="add-technology-left">
          <el-select class="add-technology-left-select" v-model="technologySelect" placeholder="选择技术">
            <el-option v-for="tech in technologies" :key="tech.id" :label="tech.name" :value="tech.id" />
          </el-select>
          <el-input class="add-technology-left-input" v-model="technologyAnnotation" placeholder="在项目中的使用情况" />
        </div>
        <div class="add-technology-right">
          <el-button @click="addTechnology">添加</el-button>
          <el-button @click="toggleAddTechnologyInterface">取消</el-button>
        </div>
      </div>
    </section>

    <EditProjectDialog ref="edit_project_dialog" @update="updateProject"></EditProjectDialog>
    <EditProjectDetailDialog ref="edit_project_detail_dialog" @update="updateProject"></EditProjectDetailDialog>
    <!-- <Loading :isLoading="loading" /> -->
  </div>
</template>

<script>
import { post } from '../../../utils/common/api'
import MarkdownIt from 'markdown-it'
import { getUser } from '../../../utils/user'
export default {
  data() {
    return {
      uid: undefined,
      id: this.$route.params.id,
      // project: {
      //   id: 1,
      //   name: '项目资产管理系统',
      //   leader: {
      //     name: 'ROOT',
      //     id: 1
      //   },
      //   current_version: '0.0.1',
      //   detail: '',
      //   start_time: {
      //     year: 2023,
      //     month: 9,
      //     day: 5
      //   },
      //   top_designer: {
      //     called: '总设计师',
      //     user: {
      //       name: 'ROOT',
      //       id: 1
      //     }
      //   },
      //   members: [
      //     {
      //       id: 1,
      //       name: 'ROOT',
      //       role: {
      //         id: 1,
      //         name: '总设计师'
      //       }
      //     },
      //     {
      //       id: 2,
      //       name: 'Monkeyhbd',
      //       role: {
      //         id: 2,
      //         name: '开发者'
      //       },
      //       annotation: '项目架构，数据库设计，后端、前端开发，技术文档'
      //     }
      //   ],
      //   technologies: [
      //     {
      //       id: 1,
      //       name: 'DocMan',
      //       annotation: '本项目使用 DocMan 构建技术文档'
      //     },
      //     {
      //       id: 2,
      //       name: 'Python',
      //     },
      //     {
      //       id: 3,
      //       name: 'Django',
      //       annotation: 'Web 后端框架、数据库 ORM'
      //     },
      //     {
      //       id: 4,
      //       name: 'HTML / CSS / JavaScript'
      //     },
      //     {
      //       id: 5,
      //       name: 'Vue',
      //       annotation: 'Web 前端框架'
      //     },
      //     {
      //       id: 6,
      //       name: 'Axios'
      //     }
      //   ],
      // },

      // 数据库数据
      project: {
        id: undefined,
        name: '',
        leader: {
          name: '',
          id: undefined
        },
        current_version: '',
        detail: '',
        start_time: {
          year: 2003,
          month: 8,
          day: 22
        },
        top_designer: {
          called: '总设计师',
          user: {
            name: '',
            id: undefined
          }
        },
        members: [
        ],
        technologies: [
        ]
      },

      addTechnologyBarEnable: false,

      technologies: [],

      technologySelect: undefined,

      technologyAnnotation: '',

      technologyTableEditEndable: false,

      memberTableEditEndable: false,

      documentTableEditEndable: false,

      repositoryTableEditEndable: false,

      addMemberBarEnable: false,

      users: [],

      userSelect: undefined,

      userRid: undefined,

      userAnnotation: '',

      projectRoles: [
        // {id: 1, name: '总设计师',project_permission: [1]},
        // {id: 2, name: '前端',project_permission: [2,3,4]},
        // {id: 3, name: '后端',project_permission: [3,4,5]},
        // {id: 4, name: '移动端',project_permission: [5]}
      ],

      repositoryList: [],

      documentList: [],

      documentName: undefined,

      documentHref: undefined,

      addDocumentBarEnable: false,

      repositoryName: undefined,

      repositoryHref: undefined,

      addRepositoryBarEnable: false,

      projectPermissionList: [
        // {
        //   id: 1,
        //   name: '所有权限',
        //   detail: '授予用户所有权限'
        // },
        // {
        //   id: 2,
        //   name: '修改项目信息',
        //   detail: '允许用户修改项目信息'
        // },
        // {
        //   id: 3,
        //   name: '修改项目成员',
        //   detail: '允许用户增加、删除、修改项目成员'
        // },
        // {
        //   id: 4,
        //   name: '设置项目身份',
        //   detail: '允许用户删除、修改或者定义新的项目身份'
        // },
        // {
        //   id: 5,
        //   name: '删除项目',
        //   detail: '允许用户删除项目'
        // },
      ],

      projectRoleTableEditEndable: false,

      addProjectRoleWidget: {
        enable: false,
        form: {
          name: ''
        }
      },

      /** 权限控制相关 */
      // 项目权限的数组
      projectPermissionArray: [],

      CurrentProjectRoleId: undefined,

      loading: false,
    }
  },

  computed: {
    projectDetail() {
      const md = new MarkdownIt()
      const result = md.render(this.project.detail)
      return result
    },
    DeletePojectPermissions() {
      return this.projectPermissionArray.includes(1) || this.projectPermissionArray.includes(5)
    },
    ProRolePermission() {
      return this.projectPermissionArray.includes(1) || this.projectPermissionArray.includes(4)
    },
    ProjectMemberPermissions() {
      return this.projectPermissionArray.includes(1) || this.projectPermissionArray.includes(3)
    },
    ChangeProjectInformationPermissions() {
      return this.projectPermissionArray.includes(1) || this.projectPermissionArray.includes(2)
    },

  },

  methods: {
    async updateProject() {
      const res = await post('/project/profile', {
        id: this.id
      })
      this.project = res
    },

    strDate(date) {
      if (date.month == undefined) {
        return `${date.year}年`
      }
      else if (date.day == undefined) {
        return `${date.year}年${date.month}月`
      }
      else {
        return `${date.year}年${date.month}月${date.day}日`
      }
    },

    updateTechnologies() {
      var that = this
      post('/technology/all', {}).then(function (res) {
        that.technologies = res.list
        console.log(that.technologies)
      })
    },

    toggleAddTechnologyInterface() {
      this.updateTechnologies()
      this.addTechnologyBarEnable = !this.addTechnologyBarEnable
      this.technologySelect = undefined
      this.technologyAnnotation = ''
    },

    addTechnology() {
      var that = this
      post('/project/technology/add', {
        pid: that.id,
        technology: {
          id: that.technologySelect,
          annotation: that.technologyAnnotation
        }
      }).then(function (res) {
        ElNotification({
          title: '添加成功',
          message: `新增了 ${res.name} 技术`,
          type: 'success',
          position: 'bottom-right',
        })
        that.toggleAddTechnologyInterface()
        that.updateProject()
      })
    },

    deleteTechnology(tid) {
      var that = this
      post('/project/technology/delete', {
        pid: that.id,
        tid: tid
      }).then(function (res) {
        ElNotification({
          title: '删除成功',
          // message: `${that.project.name} 项目新使用了 ${res.name} 技术`,
          type: 'success',
          position: 'bottom-right',
        })
        that.updateProject()
      })
    },

    toggleInTableEdit(row) {
      var that = this
      if (row.inTableEdit == undefined) {
        row.inTableEdit = {}
        row.inTableEdit.annotation = row.annotation
      }
      else {
        post('/project/technology/update', {
          tid: row.id,
          pid: that.id,
          mod: row.inTableEdit
        }).then(function (res) {
          Object.assign(row, res)
          ElNotification({
            title: '修改成功',
            message: `您刚刚修改了技术 ${res.name} ，在项目 ${that.project.name} 中的使用情况`,
            type: 'success',
            position: 'bottom-right',
          })
        })
        row.inTableEdit = undefined
      }
    },

    toggleTechnologyTableEdit() {
      this.technologyTableEditEndable = !this.technologyTableEditEndable
    },

    toggleInMemberTableEdit(row) {
      var that = this
      if (row.inTableEdit == undefined) {
        row.inTableEdit = {}
        row.inTableEdit.annotation = row.annotation
        row.inTableEdit.role = {}
        row.inTableEdit.role.id = row.role.id
      }
      else {
        post('/project/member/update', {
          uid: row.id,
          pid: that.id,
          mod: row.inTableEdit
        }).then(function (res) {
          Object.assign(row, res)
          ElNotification({
            title: '修改成功',
            message: `您刚刚修改了成员 ${res.name} 的相关信息`,
            type: 'success',
            position: 'bottom-right',
          })
        })
        row.inTableEdit = undefined
      }
    },

    updateUsers() {
      var that = this
      post('/user/all', {}).then(function (res) {
        that.users = res.list
      })
    },

    toggleAddMemberInterface() {
      this.updateUsers()
      this.addMemberBarEnable = !this.addMemberBarEnable
      this.userSelect = undefined
      this.userRid = undefined
      this.userAnnotation = ''
    },

    toggleMemberTableEdit() {
      this.memberTableEditEndable = !this.memberTableEditEndable
    },

    addMember() {
      var that = this
      post('/project/member/add', {
        pid: that.id,
        member: {
          id: that.userSelect,
          role: {
            id: that.userRid
          },
          annotation: that.userAnnotation
        }
      }).then(function (res) {
        ElNotification({
          title: '添加成功',
          message: `新增了 ${res.name} 成员`,
          type: 'success',
          position: 'bottom-right',
        })
        that.toggleAddMemberInterface()
        that.updateProject()
      })
    },

    deleteMember(member) {
      var that = this
      post('/project/member/delete', {
        uid: member.id,
        pid: that.project.id
      }).then(function (res) {
        ElNotification({
          title: '删除成功',
          message: `已将 ${res.name} 成员从此项目中移除`,
          type: 'success',
          position: 'bottom-right',
        })
        that.updateProject()
      })
    },

    openDeleteMemberConfirmMessageBox(member) {
      var that = this
      ElMessageBox.confirm(
        `将成员 ${member.name} 从 ${that.project.name} 项目中移除？`,
        '警告',
        {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'warning',
        }
      ).then(function () {
        that.deleteMember(member)
      })
    },

    openEditProjectDialog() {
      this.$refs.edit_project_dialog.setProject(this.id, this.project)
      this.$refs.edit_project_dialog.openDialog()
    },

    openEditProjectDetailDialog() {
      this.$refs.edit_project_detail_dialog.setProject(this.id, this.project)
      this.$refs.edit_project_detail_dialog.openDialog()
    },

    openDeleteProjectConfirmMessageBox() {
      var that = this
      ElMessageBox.prompt('请复述项目名字确认删除操作：', '警告', {
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      }).then(function (res) {
        if (res.action == 'confirm') {
          if (res.value == that.project.name) {
            that.deleteProject()
          }
          else {
            ElNotification({
              title: '删除中断',
              message: `您输入的字符串与项目名称不符`,
              type: 'error',
              position: 'bottom-right',
            })
          }
        }
      }).catch(function () { })
    },

    deleteProject() {
      var that = this
      post('/project/delete', {
        id: that.project.id
      }).then(function (res) {
        ElNotification({
          title: '删除成功',
          message: `成功将 No.${that.project.id} ${that.project.name} 从系统中移除`,
          type: 'success',
          position: 'bottom-right',
        })
        that.$router.back()
      })
    },

    // 项目文档
    //#region
    async updateDocument() {
      const res = post('/project/document/list', { pid: this.id })
      this.documentList = res.list
    },


    toggleDocumentTableEdit() {
      this.documentTableEditEndable = !this.documentTableEditEndable
    },

    toggleInDocumentTableEdit(row) {
      var that = this
      if (row.inTableEdit == undefined) {
        row.inTableEdit = {}
        row.inTableEdit.id = row.id
        row.inTableEdit.name = row.name
        row.inTableEdit.href = row.href
      }
      else {
        post('/project/document/update', {
          id: row.id,
          mod: row.inTableEdit
        }).then(function (res) {
          Object.assign(row, res)
          ElNotification({
            title: '修改成功',
            message: `您刚刚修改了项目${that.project.name}的文档${row.name}的信息`,
            type: 'success',
            position: 'bottom-right',
          })
          that.updateDocument()
        })
        row.inTableEdit = undefined
      }
    },

    toggleAddDocumentInterface() {
      this.addDocumentBarEnable = !this.addDocumentBarEnable
      this.documentName = undefined
      this.documentHref = undefined
    },

    addDocument() {
      var that = this
      post('/project/document/add', {
        pid: that.id,
        name: that.documentName,
        href: that.documentHref
      }).then(function (res) {
        ElNotification({
          title: '添加成功',
          message: `新增了项目${that.project.name}的文档《${res.name}》`,
          type: 'success',
          position: 'bottom-right',
        })
        that.toggleAddDocumentInterface()//关闭添加页面，清空数据
        that.updateDocument()
      })

    },

    deleteDocument(document) {
      var that = this
      post('/project/document/delete', {
        id: document.id
      }).then(function (res) {
        ElNotification({
          title: '删除成功',
          message: `删除了${that.project.name}项目下的${document.name}文档`,
          type: 'success',
          position: 'bottom-right',
        })
        that.updateDocument()
      })
    },

    openDeleteDocumentConfirmMessageBox(document) {
      var that = this
      ElMessageBox.confirm(
        `将文档 ${document.name} 从 ${that.project.name} 项目中移除?`,
        '警告',
        {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'warning',
        }
      )
        .then(() => {
          that.deleteDocument(document)
        })
        .catch(() => { })
    },
    //#endregion

    //查询项目的代码仓库列表
    //#region
    async updateRepositary() {
      const res = await post('/project/repository/list', {
        pid: this.id
      })
      this.repositoryList = res.list
    },

    toggleRepositoryTableEdit() {
      this.repositoryTableEditEndable = !this.repositoryTableEditEndable
    },

    toggleInRepositoryTableEdit(row) {
      var that = this
      if (row.inTableEdit == undefined) {
        row.inTableEdit = {}
        row.inTableEdit.name = row.name
        row.inTableEdit.href = row.href
      }
      else {
        post('/project/repository/update', {
          id: row.id,
          mod: row.inTableEdit
        }).then(function (res) {
          Object.assign(row, res)
          ElNotification({
            title: '修改成功',
            message: `您刚刚修改了代码仓库${row.name}的信息`,
            type: 'success',
            position: 'bottom-right',
          })
        })
        row.inTableEdit = undefined
      }
    },

    toggleAddRepositoryInterface() {
      this.addRepositoryBarEnable = !this.addRepositoryBarEnable
      this.repositoryName = undefined
      this.repositoryHref = undefined
    },

    addRepository() {
      var that = this
      post('/project/repository/add', {
        pid: that.id,
        name: that.repositoryName,
        href: that.repositoryHref
      }).then(function (res) {
        ElNotification({
          title: '添加成功',
          message: `新增了代码仓库`,
          type: 'success',
          position: 'bottom-right',
        })
        that.toggleAddRepositoryInterface()
        that.updateRepositary()
      })
    },

    deleteRepository(repository) {
      var that = this
      post('/project/repository/delete', {
        id: repository.id
      }).then(function (res) {
        ElNotification({
          title: '删除成功',
          message: `删除了代码仓库:${repository.name}`,
          type: 'success',
          position: 'bottom-right',
        })
        that.updateRepositary()
      })
    },

    openDeleteRepositoryConfirmMessageBox(repository) {
      var that = this
      ElMessageBox.confirm(
        `将代码仓库 ${repository.name} 从 ${that.project.name} 项目中移除?`,
        '警告',
        {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'warning',
        }
      )
        .then(() => {
          that.deleteRepository(repository)
        })
        .catch(() => { })
    },
    //#endregion

    // 项目身份
    async getPermissionList() {
      const res = await post('/project/permission/list', { pid: this.id })
      this.projectPermissionList = res.list
    },

    async updateProjectRoles() {
      const res = await post('/project/role/list', {
        id: this.id
      })
      this.projectRoles = res.list
    },

    toggleProjectRoleEidt() {
      this.projectRoleTableEditEndable = !this.projectRoleTableEditEndable
    },

    toggleInprojectRoleTableEdit(row) {
      var that = this
      if (row.inTableEdit == undefined) {
        row.inTableEdit = {
          inTableRecordProjectPermissions: [],
          name: '',
          permissions: []
        }
        row.inTableEdit.inTableRecordProjectPermissions = [0, 0, 0, 0, 0, 0]
        row.permissions.forEach(item => {
          row.inTableEdit.inTableRecordProjectPermissions[item] = 1
        })
        row.inTableEdit.name = row.name
      } else {
        row.inTableEdit.inTableRecordProjectPermissions.forEach((item, index) => {
          if (item == true) {
            row.inTableEdit.permissions.push(index)
          }
        })
        post('/project/role/update', {
          rid: row.id,
          mod: row.inTableEdit
        }).then(function (res) {
          Object.assign(row, res)
          ElNotification({
            title: '修改成功',
            message: `您刚刚更改了项目身份 ${res.name} 的项目权限`,
            type: 'success',
            position: 'bottom-right',
          })
          that.updateProjectRoles()
        })
        row.inTableEdit = undefined
      }
    },

    toggleAddProjectRoleBox() {
      this.addProjectRoleWidget.enable = !this.addProjectRoleWidget.enable
      this.addProjectRoleWidget.form.name = ''
    },


    addProjectRole() {
      var that = this
      post('/project/role/add', {
        id: this.project.id,
        name: this.addProjectRoleWidget.form.name
      }).then(function (res) {
        ElNotification({
          title: '创建成功',
          message: `您刚刚在${that.project.name}项目中添加了新的项目身份 ${res.name} (${res.rid})`,
          type: 'success',
          position: 'bottom-right',
        })
        that.toggleAddProjectRoleBox()
        that.updateProjectRoles()
      })

    },

    deleteProjectRole(projectRole) {
      var that = this
      post('/project/role/delete', {
        rid: projectRole.id
      }).then(function (res) {
        ElNotification({
          title: '删除成功',
          message: `删除了${this.project.name}项目下的项目身份 ${res.name} (${res.rid})`,
          type: 'success',
          position: 'bottom-right',
        })
        that.updateProjectRoles()
      })
    },

    openDeleteprojectRoleConfirmMessageBox(projectRole) {
      var that = this
      ElMessageBox.confirm(
        `将项目身份"${projectRole.name}"从项目中移除 `,
        '警告',
        {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'warning',
        }
      )
        .then(() => {
          that.deleteProjectRole(projectRole)
        })
        .catch(() => { })
    },
    /**
     * 项目权限控制
     */
    async getCurrentProjectRoleId() {
      let that = this;
      try {
        const res = await post('/project/member/profile', {
          uid: that.usePermission.id,
          pid: that.id
        });
        that.CurrentProjectRoleId = res.role.id;
      } catch (error) {
        console.error('Error in getCurrentProjectRoleId:', error);
      }
    },

    async getCurrentProjectPermissionList() {
      let that = this;
      try {
        await this.getCurrentProjectRoleId(); // 确保在调用之前获取到角色ID
        const res = await post('/project/role/profile', {
          rid: that.CurrentProjectRoleId
        });
        that.projectPermissionArray = res.permissions
      } catch (error) {
        console.error('Error in getCurrentProjectPermissionList:', error);
      }
    },

    async loadData() {
      this.loading = true
      await Promise.all([
        this.updateProject(),
        this.updateRepositary(),
        this.updateDocument(),
        this.updateProjectRoles(),
        this.getPermissionList(),
        this.getCurrentProjectPermissionList()
      ])
      this.loading = false
    }
  },

  mounted() {
    this.loadData()
  },
}
</script>

<style scoped>
.project-page-head {
  margin-bottom: 40px;
}

.info-container {
  padding: 20px 0;
}

.descriptions-list {
  width: 100%;
}

.descriptions-title {
  display: flex;
  align-items: center;
}

.descriptions-title-icon {
  margin-right: 8px;
}

.project-detail {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 24px;
  text-align: left;
  font-size: 15px;
}

.add-technology-box {
  display: flex;
  margin-top: 8px;
}

.add-technology-left {
  display: flex;
  flex-grow: 1;
  padding-right: 12px;
}

.add-technology-left>* {
  margin-right: 8px;
}

.add-technology-right {
  flex-grow: 0;
}

.add-role-box {
  display: flex;
  margin-top: 8px;
}

.add-role-left {
  display: flex;
  flex-grow: 1;
  padding-right: 12px;
}

.add-role-left>* {
  margin-right: 8px;
}

.add-role-right {
  flex-grow: 0;
}
</style>
